package jdklearning.net.bio;

import org.apache.commons.lang3.RandomUtils;

import java.io.IOException;
import java.io.InputStream;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;
import java.util.Set;

/**
 * @author shenenlu 2021年06月11日 下午17:11:05
 */
public class BioServer implements Runnable{


    @Override
    public void run() {
        try {
            ServerSocket serverSocket =
                    new ServerSocket(9999);
            Socket accept = serverSocket.accept();
            byte[] bytes = new byte[1024];
            int read = accept.getInputStream().read(bytes);
            System.out.println(new String(bytes));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket =
                new ServerSocket(9999);
        Set<Socket> socketSet = new HashSet<>();
        new Thread(() -> {
            while (true){
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                socketSet.forEach( r-> {
                    try {
                        r.getOutputStream().write(String.valueOf(RandomUtils.nextInt()).getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
            }
        }).start();
        byte[] bytes = new byte[1024];
        while (true){
            Socket accept = serverSocket.accept();//阻塞
            socketSet.add(accept);
            InputStream inputStream = accept.getInputStream();
            int read = inputStream.read(bytes);//阻塞
            System.out.println(read);
            System.out.println(new String(bytes, 0 ,read));
            System.out.println(socketSet);
//            for( Socket socket : socketSet ){
//                OutputStream outputStream = socket.getOutputStream();
//                outputStream.write("back".getBytes());
//                outputStream.flush();
//            }
        }
    }
}
